<template>
    <div class="teammsg">
        <pagetitle></pagetitle>
        <el-card>
            <el-form :model="pageData" ref="formRef" class="formbox" label-width="140px" :disabled="formDisabled" label-position="right">
                <div class="formboxitem">
                    <div class="title">团队基本信息</div>
                    <el-form-item
                        label="团队名称："
                        prop="teamName"
                        :rules="[
                            {
                                required: true,
                                message: '请输入团队名称',
                            },
                        ]"
                    >
                        <el-input v-model="pageData.teamName" class="inputs" placeholder="请输入团队名称"></el-input>
                        <span class="formTip">*团队名称</span>
                    </el-form-item>
                    <el-form-item label="团队简称：">
                        <el-input v-model="pageData.nameForShort" class="inputs" placeholder="请输入团队简称"></el-input>
                        <span class="formTip">*团队简称</span>
                    </el-form-item>
                    <el-form-item label="团队LOGO：">
                        <div>
                            <uploadFile :fileUrl="pageData.teamLogo" @callBack="uploadFiles" tableItem="cardPositive" width="120px" height="120px" :showIconOrText="true" :showText="false" iconSize="30" v-if="componentsshow"></uploadFile>
                            <div class="uploadcertificateTitle">● 图片格式要求jpg、jpeg、bmp、png、pdf，不超过10M。</div>
                        </div>
                    </el-form-item>
                    <el-form-item
                        label="注册地址："
                        prop="address"
                        :rules="[
                            {
                                required: true,
                            },
                            { validator: addre },
                        ]"
                    >
                        <addRess :value="pageData.address.keyText" v-if="componentsshow" :getAreaData="getAreaData" class="inputs"></addRess>
                        <span class="formTip">*团队注册地址</span>
                    </el-form-item>
                </div>
                <div class="formboxitem">
                    <div class="title">团队管理信息</div>
                    <el-form-item
                        label="您的角色："
                        prop="creatorRole"
                        :rules="[
                            {
                                required: true,
                                message: '请选择您的角色',
                            },
                        ]"
                    >
                        <radiobutton :data="cardType" v-model="pageData.creatorRole" :disabled="formDisabled"></radiobutton>
                    </el-form-item>
                    <el-form-item
                        label="法人名字："
                        prop="legalPersonName"
                        :rules="[
                            {
                                required: true,
                                message: '请输入法人名字',
                            },
                        ]"
                    >
                        <el-input v-model="pageData.legalPersonName" class="inputs" placeholder="请输入名字"></el-input>
                        <span class="formTip">*团队法人名字</span>
                    </el-form-item>
                    <el-form-item
                        label="法人电话："
                        prop="legalPersonPhone"
                        :rules="[
                            {
                                required: true,
                                message: '请输入法人电话',
                            },
                        ]"
                    >
                        <el-input v-model="pageData.legalPersonPhone" class="inputs" placeholder="请输入手机号码"></el-input>
                        <span class="formTip">*团队法人联系方式</span>
                    </el-form-item>
                </div>
                <div class="formboxitem">
                    <div class="title">团队分类信息</div>
                    <el-form-item
                        label="机构类型："
                        prop="classificationId"
                        :rules="[
                            {
                                required: true,
                                message: '请选择机构类型',
                            },
                        ]"
                    >
                        <el-cascader ref="institutionalTypecascader" v-model="pageData.classificationId" class="inputs" placeholder="请选择机构类型" :props="props"></el-cascader>
                        <span class="formTip">*参考标准：GB/T 20091-2006 组织机构类型</span>
                    </el-form-item>

                    <!-- <el-form-item label="机构类型说明：">
                        <el-input v-model="pageData.content" :rows="6" resize="none" disabled type="textarea" placeholder=""></el-input>
                    </el-form-item> -->
                    <!-- <el-form-item
                        label="产业分类："
                        prop="industrialClassificationIds"
                        :rules="[
                            { validator: classify },
                            {
                                required: true,
                            },
                        ]"
                    > -->
                    <div v-if="pageData.classificationId.length > 0">
                        <el-form-item label="机构级别：" v-if="pageData.classificationId[0] != '12'">
                            <addRess
                                :value="pageData.organizationlevel ? pageData.organizationlevel.keyText : ''"
                                :checkStrictly="true"
                                v-if="componentsshow"
                                placeholder="请选择机构级别"
                                :getAreaData="getOrganizationlevel"
                                class="inputs"
                            ></addRess>
                        </el-form-item>
                        <div v-else>
                            <el-form-item label="产业分类：">
                                <div class="selectorbtn" style="margin-right: 0">
                                    <el-cascader v-model="industrialClassificationIdsValues" placeholder="请选择产业分类" ref="industrialClassificationcascader" class="inputs" :props="props1" @change="handleChange"></el-cascader>
                                    <!-- <div class="selectorbtn_btn" @click="addindustrialClassificationIds">添加</div> -->
                                </div>
                                <span class="formTip">*参考标准：GB/T 4754-2017 国民经济行业分类</span>
                            </el-form-item>
                            <el-form-item label="" v-if="industrialClassificationIdsTexts.length > 0">
                                <div class="classfiy">
                                    <div v-for="(tag, index) in industrialClassificationIdsTexts" :key="index">
                                        <el-tag closable @close="handleClose(index)">
                                            {{ tag }}
                                        </el-tag>
                                    </div>
                                </div>
                            </el-form-item>
                            <el-form-item label="产业分类说明：">
                                <el-input v-model="pageData.illustrate" :rows="6" resize="none" disabled type="textarea" placeholder=""></el-input>
                            </el-form-item>
                        </div>
                    </div>
                </div>
                <el-form-item label="" class="btnformitem">
                    <div class="formboxitem" v-if="pageType.type == '1' || pageType.type == '3'">
                        <sxnfbtn @click="router.back()">返回</sxnfbtn>
                        <sxnfbtn @click="submit(formRef)" v-if="pageType.type != '2'">{{ pageType.type == "1" ? "创建" : "修改" }}</sxnfbtn>
                        <!-- <sxnfbtn v-if="pageType.type != '1' && pageType.type != '2'" @click="outTheTeam">退出团队</sxnfbtn> -->
                        <sxnfbtn v-if="pageType.type != '1' && pageType.type != '2'" @click="outTheTeam">退出团队</sxnfbtn>
                        <!-- <el-button class="submitbtn" bg text @click="router.back()">返回</el-button> -->
                        <!-- <el-button class="submitbtn" bg text @click="submit(formRef)" v-if="pageType.type != '2'">{{ pageType.type == "1" ? "创建" : "修改" }}</el-button> -->
                        <!-- <el-button class="submitbtn" bg text v-if="pageType.type != '1' && pageType.type != '2'" @click="outTheTeam">退出团队</el-button> -->
                    </div>
                </el-form-item>
            </el-form>
            <div class="formboxitems" v-if="pageType.type == '4' || pageType.type == '2'">
                <sxnfbtn @click="router.back()">返回</sxnfbtn>
                <sxnfbtn @click="applytojoin" v-if="pageType.type == '4'" :disabled="pageData.invitation_status == '0' ? false : true">
                    {{ pageData.invitation_status == "0" ? "申请加入" : pageData.invitation_status == "1" ? "审核中" : "已加入" }}
                </sxnfbtn>
                <!-- <el-button class="submitbtn" bg text @click="router.back()">返回</el-button> -->
                <!-- <el-button class="submitbtn" bg text @click="applytojoin" v-if="pageType.type == '4'" :disabled="pageData.invitation_status == '0' ? false : true">
                    {{ pageData.invitation_status == "0" ? "申请加入" : pageData.invitation_status == "1" ? "审核中" : "已加入" }}
                </el-button> -->
            </div>
        </el-card>
        <!-- -->
        <div class="submitsuccessfully" v-if="submitsuccessfully">
            <div class="contMsg">
                <div class="title">创建团队已完成</div>
                <img src="../../../assets/images/success.png" alt="" srcset="" />
                <div class="success">请及时对团队进行 <span>实名认证</span></div>
                <div class="tipcg">实名认证后，团队可以开通更多功能。</div>
                <sxnfbtn class="btnzdl" @click="router.back()">知道了</sxnfbtn>
                <!-- <div class="btnzdl" @click="router.back()">知道了</div> -->
            </div>
        </div>
        <!-- -->
        <div class="submitsuccessfully" v-if="jointeamPop">
            <div class="contMsg">
                <div class="title">提交完成</div>
                <img src="../../../assets/images/success.png" alt="" srcset="" />
                <div class="success">
                    申请加入 已提交到<span>{{ pageData.teamName }}公司</span>
                </div>
                <div class="tipcg">您已成功提交申请，等待团队管理确认后，开通本团队功能。</div>
                <sxnfbtn class="btnzdl" @click="router.back()">知道了</sxnfbtn>
                <!-- <div class="btnzdl" @click="router.back()">知道了</div> -->
            </div>
        </div>
    </div>
</template>
<script lang="ts" setup>
import { institutionalType, industrialClassifications, createdTeam, teamMsg, updateTeamMsg, institutionalTypeOne, industrialClassificationsOne, applyToJoin, outToJoin } from "@/api/team";
import type { CascaderProps } from "element-plus";
import { ElMessage, ElMessageBox } from "element-plus";
// import mars3d from "@/components/mars3d.vue";
import { ref, reactive } from "vue";
import { useRouter, useRoute } from "vue-router";
import type { FormInstance } from "element-plus";
import Jointeam from "./jointeam.vue";

// import { companyInfo } from "@/api/team";
let componentsshow: any = ref(false);
setTimeout(() => {
    componentsshow.value = true;
}, 10);
const router = useRouter();
const route = useRoute();
const cardType = ref([
    {
        label: "法人",
        value: 1,
    },
    {
        label: "授权管理员",
        value: 2,
    },
]);
let pageData: any = ref({
    teamId: "",
    teamName: "",
    nameForShort: "",
    teamLogo: "",
    creatorRole: 1,
    legalPersonName: "",
    legalPersonPhone: "",
    address: {},
    classificationId: [],
    type: "",
    // content: "",
    industrialClassificationIds: [],
    userId: "",
    seq: "",
    illustrate: "",
    organizationlevel: {},
});
// 机构类型数据懒加载
const props: CascaderProps = {
    label: "type",
    value: "classificationId",
    lazy: true,
    lazyLoad(node: any, resolve) {
        const { data, level } = node;
        institutionalType(data.classificationId ? data.classificationId : 0).then((res) => {
            res.data.forEach((v: any) => {
                institutionalType(v.classificationId).then((res1) => {
                    if (res1.data.length == 0) {
                        v.leaf = true;
                    } else {
                        v.leaf = false;
                    }
                });
            });
            setTimeout(() => {
                resolve(res.data);
            }, 500);
        });
    },
};
const institutionalTypecascader: any = ref(null);
// 机构类型显示说明
// const institutionalTypeChange = (e: any) => {
//     let node = institutionalTypecascader.value.getCheckedNodes()[0];
//     // pageData.value.content = node.data.content;
// };
// 产业分类数据懒加载
const industrialClassificationIdsValues: any = ref([]);
const props1: CascaderProps = {
    checkStrictly: true,
    label: "industrialName",
    value: "industrialId",
    lazy: true,
    lazyLoad(node: any, resolve) {
        const { data, level } = node;
        industrialClassifications(data.industrialId ? data.industrialId : 0).then((res) => {
            res.data.forEach((v: any) => {
                industrialClassifications(v.industrialId).then((res1) => {
                    if (res1.data.length == 0) {
                        v.leaf = true;
                    } else {
                        v.leaf = false;
                    }
                });
            });
            setTimeout(() => {
                resolve(res.data);
            }, 500);
        });
    },
};
// 产业分类显示说明
const industrialClassificationIdsTexts: any = ref([]);
const industrialClassificationcascader: any = ref(null);
const handleChange = (value: any) => {
    let node = industrialClassificationcascader.value.getCheckedNodes()[0];
    pageData.value.illustrate = node.data.illustrate;
    setTimeout(() => {
        addindustrialClassificationIds();
        industrialClassificationcascader?.value.togglePopperVisible();
    }, 300);
};
// 添加行业分类
const addindustrialClassificationIds = () => {
    if (formDisabled.value) {
        return;
    }
    let node = industrialClassificationcascader.value.getCheckedNodes()[0];
    if (node) {
        industrialClassificationIdsTexts.value.push(node.text);
        pageData.value.industrialClassificationIds.push(node.pathValues[node.pathValues.length - 1]);
    }
};
// 移除产业分类
const handleClose = (i: number) => {
    pageData.value.industrialClassificationIds.splice(i, 1);
    industrialClassificationIdsTexts.value.splice(i, 1);
};
// logo
const uploadFiles = (e: any, a: any) => {
    pageData.value.teamLogo = e;
};

// 地址
const getAreaData = (data: object) => {
    pageData.value.address = data;
    console.log(data);
};
// 机构级别
const getOrganizationlevel = (data: object) => {
    pageData.value.organizationlevel = data;
};
const formRef = ref<FormInstance>();
const addre = (rule: any, value: any, callback: any) => {
    setTimeout(() => {
        if (pageData.value.address && pageData.value.address.keyText) {
            callback();
        } else {
            callback(new Error("请选择注册地址"));
        }
    }, 300);
};
// const classify = (rule: any, value: any, callback: any) => {
//     setTimeout(() => {
//         if (industrialClassificationIdsTexts.value.length > 0) {
//             callback();
//         } else {
//             callback(new Error("请选择产业分类"));
//         }
//     }, 300);
// };
// 提交数据
//弹窗
const submitsuccessfully = ref(false);
const submit = (formEl: FormInstance | undefined) => {
    if (!formEl) return;
    // console.log(formEl);
    // return;
    formEl.validate((valid) => {
        if (valid) {
            // console.log(valid);
            // return;
            pageData.value.classificationId = pageData.value.classificationId[pageData.value.classificationId.length - 1];
            pageData.value.address = JSON.stringify(pageData.value.address);
            if (pageData.value.organizationlevel) {
                pageData.value.organizationlevel = JSON.stringify(pageData.value.organizationlevel);
            } else {
                pageData.value.organizationlevel = "";
            }

            // console.log(pageData.value.organizationlevel);
            if (pageType.type == "1") {
                // 创建团队
                createdTeam(pageData.value).then((res) => {
                    // ElMessage({
                    //     message: "创建成功",
                    //     type: "success",
                    // });

                    // router.back();
                    submitsuccessfully.value = true;
                });
            } else if (pageType.type == "3") {
                // 修改
                pageData.value.teamId = pageType.id;
                updateTeamMsg(pageData.value).then((res) => {
                    ElMessage({
                        message: "修改成功",
                        type: "success",
                    });
                    router.back();
                });
            }
        }
    });
};
// console.log(route);
const getTeamMsg = () => {
    teamMsg(pageType.id).then((res: any) => {
        pageData.value = res.data;
        if (!pageData.value.invitation_status) {
            pageData.value.invitation_status = 0;
        }
        if (pageData.value.address) {
            pageData.value.address = JSON.parse(pageData.value.address);
        } else {
            pageData.value.address = {};
        }
        if (pageData.value.organizationlevel) {
            pageData.value.organizationlevel = JSON.parse(pageData.value.organizationlevel);
        } else {
            pageData.value.organizationlevel = {};
        }
        // return;
        // console.log(pageData);
        if (pageData.value.classificationId) {
            let id: number = pageData.value.classificationId;
            pageData.value.classificationId = [];
            pageData.value.classificationId.length = 0;
            institutionaltype(id);
        }

        pageData.value.industrialClassificationIds = [];
        pageData.value.industrialClassificationIds.length = 0;
        if (pageData.value.industrialClassificationList.length > 0) {
            let array = pageData.value.industrialClassificationList;
            array.forEach((v: any, i: any) => {
                industrialclassification(v.industrialId, [], []);
            });
        }
    });
};
// 页面类型
const pageType: any = route.query;
const formDisabled = ref(false);
if (pageType.type == "1") {
    // 从我的团队页面进入
    formDisabled.value = false;
    route.meta.title = "创建团队";
} else if (pageType.type == "2" || pageType.type == "4") {
    // 从加入团队页面搜索进入
    formDisabled.value = true;
    route.meta.title = "团队详情";
    getTeamMsg();
} else if (pageType.type == "3") {
    // 从加入团队页面我的邀请进入
    formDisabled.value = false;
    route.meta.title = "团队编辑";
    getTeamMsg();
}
// 申请加入团队
const jointeamPop = ref(false);
const applytojoin = () => {
    applyToJoin(pageType.id).then((res: any) => {
        // ElMessage.success("申请成功，请等待管理员审核！");
        // router.back();
        // console.log(res);
        jointeamPop.value = true;
    });
};
// 退出团队
const outTheTeam = () => {
    ElMessageBox.confirm("确定要退出该团队吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
    }).then(() => {
        outToJoin(pageType.id).then((res: any) => {
            ElMessage.success("退出成功！");
            router.back();
        });
    });
};
// 数据回显，
// 递归查询机构类型
const institutionaltype = (id: number | string) => {
    institutionalTypeOne(id).then((res: any) => {
        let data: any = res.data;
        // console.log(data);
        // retuen;
        if (data.classificationId) {
            pageData.value.classificationId.unshift(data.classificationId);
        }
        if (data.parentId != 0) {
            institutionaltype(data.parentId);
        }
    });
};
// 递归查询产业分类 industrialClassificationIdsTexts
const industrialclassification = (id: number | string, idList: any | [], array: any | []) => {
    industrialClassificationsOne(id).then((res) => {
        const data: any = res.data;
        array.unshift(data.industrialName);
        idList.unshift(data.industrialId);
        if (data.parentId != 0) {
            industrialclassification(data.parentId, idList, array);
        } else {
            pageData.value.industrialClassificationIds.push(idList[idList.length - 1]);
            industrialClassificationIdsTexts.value.push(array.join("/"));
        }
        // console.log(array);
    });
};
</script>

<style scoped lang="scss">
.formboxitems {
    border-top: 1px solid #eeeeee;
    padding-top: 20px;
    margin-top: 30px;
}

.submitsuccessfully {
    position: fixed;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background: rgba(51, 51, 51, 0.1);
    z-index: 999;
    .contMsg {
        width: 435px;
        height: 327px;
        background: #ffffff;
        border-radius: 5px 5px 5px 5px;
        position: absolute;
        left: 0;
        top: 0;
        right: 0;
        bottom: 0;
        margin: auto;
        // transform: scale(0.7);
        .title {
            text-align: center;
            margin-top: 33px;
            font-weight: bold;
            font-size: 20px;
            color: #333333;
        }
        img {
            width: 50px;
            position: relative;
            left: 50%;
            transform: translateX(-50%);
            margin-top: 38px;
            margin-left: 5px;
        }
        .success {
            font-weight: normal;
            font-size: 16px;
            color: #333333;
            margin-top: 38px;
            text-align: center;
            span {
                color: #ff0000;
            }
        }
        .tipcg {
            font-size: 14px;
            color: #999999;
            text-align: center;
            margin-top: 16px;
            padding: 0;
        }
        .btnzdl {
            width: 100px;
            // height: 47px;
            // background: #299c37;
            position: relative;
            left: 50%;
            transform: translateX(-50%);
            text-align: center;
            // line-height: 47px;
            cursor: pointer;
            margin-top: 30px;
            // font-size: 20px;
            color: #ffffff;
        }
    }
}
.formboxitemSunmitBtn {
    padding: 0 15px;
    height: 29px;
    line-height: 29px;
    margin-left: 12px;
    color: #23b14d;
    border-radius: 5px;
    background-color: #f5f7fa;
    cursor: pointer;
    display: inline-block;
    outline: none;
    border: none;
    &:hover {
        background-color: #23b14d;
        color: #f5f7fa !important;
    }
}
</style>
<style>
.teammsg .btnformitem .el-form-item__content {
    margin-left: 0 !important;
}
</style>
